package cn.virens.library.http.response;

import android.text.TextUtils;

/**
 * 数据解析异常
 * Created by loioi on 2017/1/17.
 */
public class ResponseException extends Exception {
    private ServerResponse response;
    private String detailMessage;

    public ResponseException() {
        this(null, null, null);
    }

    public ResponseException(String message) {
        this(message, null, null);
    }

    public ResponseException(String message, Throwable cause) {
        this(message, null, cause);
    }

    public ResponseException(String message, ServerResponse response) {
        this(message, response, null);
    }

    public ResponseException(ServerResponse response) {
        this(null, response, null);
    }

    public ResponseException(ServerResponse response, Throwable cause) {
        this(null, response, cause);
    }

    public ResponseException(String message, ServerResponse response, Throwable cause) {
        this.fillResponse(response);
        this.fillMessage(message);
        this.fillInStackTrace();
        this.fillCause(cause);
    }

    @Override
    public String getMessage() {
        if (response != null) {
            return response.msg();
        } else if (!TextUtils.isEmpty(detailMessage)) {
            return detailMessage;
        } else {
            return super.getMessage();
        }
    }

    public ServerResponse response() {
        return response;
    }

    public Throwable fillCause(Throwable cause) {
        if (cause != null) super.initCause(cause);

        return this;
    }

    public void fillMessage(String detailMessage) {
        this.detailMessage = detailMessage;
    }

    public void fillResponse(ServerResponse response) {
        this.response = response;
    }

}
